<template>
    <div class="code-extractor">
        <h2>查找不存在的Code项 (不去重)</h2>
        <button @click="findMissingItems" :disabled="isLoading">查找不存在的Code</button>
        <!-- <div>JSON数据长度: {{ (json220105 as any[]).length }}</div>
        <div>JSON数据长度: {{ (json220112 as any[]).length }}</div>
        <div>JSON数据长度: {{ (json220113 as any[]).length }}</div>
        <div>JSON数据长度: {{ (json220122 as any[]).length }}</div>
        <div>JSON数据长度: {{ (json220182 as any[]).length }}</div>
        <div>JSON数据长度: {{ (json220183 as any[]).length }}</div> -->
        <div>JSON数据长度: {{ (code as any[]).length }}</div>
        <div v-if="isLoading" class="loading">
            正在处理中，请稍候...
        </div>

        <div v-if="error" class="error">
            {{ error }}
        </div>

        <div v-if="missingItems.length > 0" class="results">
            <h3>查找结果 (共{{ missingItems.length }}个前九位不在town中的项，不去重)</h3>

            <div class="comparison-results">
                <h4>不存在的Code项 (显示12位code和name):</h4>
                <div class="code-string-container">
                    {{ missingItemsString }}
                </div>
                <button @click="copyToClipboard(missingItemsString)">复制</button>
            </div>

            <div class="missing-codes-list">
                <table>
                    <thead>
                        <tr>
                            <th>Code (12位)</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item, index) in missingItems" :key="index">
                            <td>{{ item.code }}</td>
                            <td>{{ item.name }}</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { extractCodesFromObject } from '../utils/extractCodes';
import json220105 from '../json/220105.json';
import json220112 from '../json/220112.json'
import json220113 from '../json/220113.json'
import json220122 from '../json/220122.json'
import json220182 from '../json/220182.json'
import json220183 from '../json/220183.json'
import code from '../json/公主岭村+编码.json'
import town from '../json/townGZL.json';

// 存储不存在于town中的完整项目（包含code和name）
const missingItems = ref<Array<{ code: string, name: string }>>([]);
const isLoading = ref(false);
const error = ref('');

// 计算缺失项的字符串表示，格式为：code,name
const missingItemsString = computed(() => {
    return missingItems.value.map(item => `${item.code},${item.name}`).join('\n');
});

const findMissingItems = async () => {
    isLoading.value = true;
    error.value = '';

    try {
        // 创建一个Set来存储town中的所有code，便于快速查找
        const townCodesSet = new Set(town);

        // 存储结果，不进行去重
        const result: Array<{ code: string, name: string }> = [];

        // 递归函数，用于遍历JSON对象中的所有属性
        const processItem = (obj: any) => {
            if (!obj || typeof obj !== 'object') return;

            // 如果对象有code和name属性
            if (obj.hasOwnProperty('code') && obj.hasOwnProperty('name') && typeof obj.code === 'string') {
                // 获取code的前9位
                const codePrefix = obj.code.substring(0, 9);

                // 检查前9位是否在town中存在
                if (!townCodesSet.has(codePrefix)) {
                    // 添加完整的项目（12位code和name），不进行去重
                    result.push({
                        code: obj.code,
                        name: obj.name
                    });
                }
            }

            // 遍历对象的所有属性
            for (const key in obj) {
                if (obj.hasOwnProperty(key)) {
                    const value = obj[key];

                    // 如果属性值是数组
                    if (Array.isArray(value)) {
                        value.forEach(item => processItem(item));
                    }
                    // 如果属性值是对象
                    else if (typeof value === 'object' && value !== null) {
                        processItem(value);
                    }
                }
            }
        };

        // 开始递归遍历
        // processItem(json220105);
        // processItem(json220112);
        // processItem(json220113);
        // processItem(json220122);
        // processItem(json220182);
        // processItem(json220183);
        processItem(code);
        missingItems.value = result;
    } catch (err) {
        error.value = `查找失败: ${err instanceof Error ? err.message : String(err)}`;
    } finally {
        isLoading.value = false;
    }
};

const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text)
        .then(() => {
            alert('已复制到剪贴板!');
        })
        .catch(err => {
            console.error('复制失败:', err);
            alert('复制失败，请手动复制');
        });
};
</script>

<style scoped>
.code-extractor {
    /* max-width: 800px; */
    margin: 0 auto;
    padding: 20px;
}

.loading {
    margin: 20px 0;
    color: #666;
}

.error {
    margin: 20px 0;
    color: #f00;
}

.results {
    margin-top: 20px;
}

.codes-string,
.comparison-results {
    margin: 20px 0;
}

.code-string-container {
    max-height: 200px;
    overflow-y: auto;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-bottom: 10px;
    word-break: break-all;
    white-space: pre-wrap;
    font-family: monospace;
}

.codes-list,
.missing-codes-list {
    margin-top: 20px;
}

.missing-codes-list {
    max-height: 400px;
    overflow-y: auto;
}

table {
    width: 100%;
    border-collapse: collapse;
}

th,
td {
    padding: 8px;
    text-align: left;
    border-bottom: 1px solid #ddd;
}

th {
    /* background-color: #f2f2f2; */
    position: sticky;
    top: 0;
}

tr:hover {
    /* background-color: #f5f5f5; */
}

button {
    padding: 8px 16px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    margin: 5px 0;
}

button:hover {
    background-color: #45a049;
}

button:disabled {
    background-color: #cccccc;
    cursor: not-allowed;
}
</style>